<template>
  <div style="height:4vh;background-color:#fff;">
    <el-card style="margin:10px;height: 100px">
      <el-row :gutter="14">
        <el-col :span="3">
          <div class="statistic-card">
            <el-statistic :value=assetCount >
              <template #title>
                <div style="display: inline-flex; align-items: center">
                  固定资产总数
                  <el-tooltip
                      effect="dark"
                      content="目前公司总固定资产数量"
                      placement="top"
                  >
                    <el-icon style="margin-left: 4px" :size="12">
                      <Warning />
                    </el-icon>
                  </el-tooltip>
                </div>
              </template>
            </el-statistic>
          </div>
        </el-col>
        <el-col :span="3">
          <div class="statistic-card">
            <el-statistic :value=deptCount>
              <template #title>
                <div style="display: inline-flex; align-items: center">
                  部门数
                  <el-tooltip
                      effect="dark"
                      content="公司部门总数"
                      placement="top"
                  >
                    <el-icon style="margin-left: 4px" :size="12">
                      <Warning />
                    </el-icon>
                  </el-tooltip>
                </div>
              </template>
            </el-statistic>
          </div>
        </el-col>
        <el-col :span="3">
          <div class="statistic-card">
            <el-statistic :value=userCount >
              <template #title>
                <div style="display: inline-flex; align-items: center">
                  员工数
                  <el-tooltip
                      effect="dark"
                      content="公司员工总数"
                      placement="top"
                  >
                    <el-icon style="margin-left: 4px" :size="12">
                      <Warning />
                    </el-icon>
                  </el-tooltip>
                </div>
              </template>
            </el-statistic>
          </div>
        </el-col>
        <el-col :span="3">
          <div class="statistic-card">
            <el-statistic :value=atteCount title="今日打卡数">
              <template #title>
                <div style="display: inline-flex; align-items: center">
                  今日打卡数
                </div>
                <el-tooltip
                    effect="dark"
                    content="本日所有打卡数量"
                    placement="top"
                >
                  <el-icon style="margin-left: 4px" :size="12">
                    <Warning />
                  </el-icon>
                </el-tooltip>
              </template>
            </el-statistic>
          </div>
        </el-col>
        <el-col :span="3">
          <div class="statistic-card">
            <el-statistic :value=atteCount>
              <template #title>
                <div style="display: inline-flex; align-items: center">
                  打卡数/员工数
                </div>
              </template>
              <template #suffix>/{{userCount}}</template>
            </el-statistic>
          </div>
        </el-col>
        <el-col :span="9" style="display: flex">
          <el-text style="font-size: 30px;margin: auto;">{{currentTime}}</el-text>
        </el-col>
      </el-row>
    </el-card>
    <el-row :gutter="14">
      <!--   左下     -->
      <el-col :span="18">
      <!--   中间常用功能     -->
        <el-card style="margin:10px;height: 100px;position: relative">
          <el-row :gutter="20">
            <el-col :span="4" @click="toAtt">
              <div class="block">
                <!-- 消息图标和未读消息提示 -->
                <div class="message-icon" @click="showMessages">
                  <span v-if="unreadCount > 0" class="badge">{{ unreadCount }}</span>
                </div>
                <img src="/imgs/admin/att1.png" width="50px">
                <span class="dot_title">考勤</span>
              </div>
            </el-col>
            <el-col :span="4" @click="toEmp">
              <div class="block">
                <!-- 消息图标和未读消息提示 -->
                <div class="message-icon" @click="showMessages2">
                  <span v-if="unreadCount2 > 0" class="badge">{{ unreadCount2 }}</span>
                </div>
                <img src="/imgs/admin/emp1.png" width="50px">
                <span class="dot_title">员工</span>
              </div>
            </el-col>
            <el-col :span="4" @click="toAsset">
              <div class="block">
                <!-- 消息图标和未读消息提示 -->
                <div class="message-icon" @click="showMessages3">
                  <span v-if="unreadCount3 > 0" class="badge">{{ unreadCount3 }}</span>
                </div>
                <img src="/imgs/admin/asset1.png" width="50px">
                <span class="dot_title">资产</span>
              </div>
            </el-col>
            <el-col :span="4" @click="toVehicle">
              <div class="block">
                <!-- 消息图标和未读消息提示 -->
                <div class="message-icon" @click="showMessages4">
                  <span v-if="unreadCount4 > 0" class="badge">{{ unreadCount4 }}</span>
                </div>
                <img src="/imgs/admin/car1.png" width="50px">
                <span class="dot_title">车辆</span>
              </div>
            </el-col>
            <el-col :span="4" @click="toRepair">
              <div class="block">
                <!-- 消息图标和未读消息提示 -->
                <div class="message-icon" @click="showMessages5">
                  <span v-if="unreadCount5 > 0" class="badge">{{ unreadCount5 }}</span>
                </div>
                <img src="/imgs/admin/repair1.png" width="50px">
                <span class="dot_title">维修</span>
              </div>
            </el-col>
            <el-col :span="4" @click="toNote">
              <div class="block">
                <!-- 消息图标和未读消息提示 -->
                <div class="message-icon" @click="showMessages6">
                  <span v-if="unreadCount6 > 0" class="badge">{{ unreadCount6 }}</span>
                </div>
                <img src="/imgs/admin/note1.png" width="50px">
                <span class="dot_title">备忘</span>
              </div>
            </el-col>

          </el-row>
        </el-card>
        <el-row :gutter="2">
          <!--     公告栏     -->
          <el-col :span="12">
            <el-card style="margin:10px;height: 520px;background-color: #e6c3ad">
              <div class="sub_title">《最新公告》</div>
              <el-table :data="annoList" highlight-current-row @row-click="handleChange">
                <el-table-column type="index" label="编号" width="80" align="center"/>
                <el-table-column prop="title" label="标题" :show-overflow-tooltip="true" align="center"/>
                <el-table-column prop="createTime" label="发布时间" align="center"/>
              </el-table>
              <div style="float: right;">
                <el-pagination
                    layout="total, prev, pager, next,"
                    v-model:current-page="currentPage"
                    v-model:page-size="currentSize"
                    v-model:total="total"
                    @current-change="handleCurrentChange"
                />
              </div>
            </el-card>
          </el-col>
          <!--     备忘栏     -->
          <el-col :span="12">
            <el-card style="margin:10px;height: 520px;background-color: #e6e1ad">
              <div class="sub_title">《会议备忘》</div>
              <el-table :data="noteList" highlight-current-row @row-click="handleChangeB">
                <el-table-column type="index" label="编号" width="80" align="center"/>
                <el-table-column prop="title" label="标题" :show-overflow-tooltip="true" align="center"/>
                <el-table-column prop="createTime" label="发布时间" align="center"/>
              </el-table>
              <div style="float: right;">
                <el-pagination
                    layout="total, prev, pager, next,"
                    v-model:current-page="currentPageB"
                    v-model:page-size="currentSizeB"
                    v-model:total="totalB"
                    @current-change="handleCurrentChangeB"
                />
              </div>
            </el-card>
          </el-col>
        </el-row>
      </el-col>
      <!--    右下    -->
      <el-col :span="6">
        <el-card style="margin:10px;height: 640px">
          <el-calendar v-model="value" />
        </el-card>
      </el-col>
    </el-row>
  </div>

  <!-- 查看公告详情弹窗 -->
  <el-dialog
      v-model="annoVisible"
      style="width: 1300px;padding: 20px;">
    <h2>{{annoDetail.title}}</h2>
    <hr>
    <h4>
      <span>发布人:&nbsp;<u>{{annoDetail.userId}}</u></span>&nbsp;&nbsp;|&nbsp;&nbsp;
      <span>部门:&nbsp;<u>{{annoDetail.departmentId}}</u></span>&nbsp;&nbsp;|&nbsp;&nbsp;
      <span>发布时间:&nbsp;{{annoDetail.createTime}}</span>
    </h4>

    <el-text class="mx-1" size="large">{{annoDetail.content}}</el-text>
    <el-image style="width: 300px; height: 300px;display: block;margin: 0 auto" :src="BASE_URL+annoDetail.imgUrl"  />
  </el-dialog>

  <!-- 查看备忘详情弹窗 -->
  <el-dialog
      v-model="noteVisible"
      style="width: 1300px;padding: 20px;">
    <h2>{{noteDetail.title}}</h2>
    <hr>
    <h4>
      <span>发布人:&nbsp;<u>{{noteDetail.userId}}</u></span>&nbsp;&nbsp;|&nbsp;&nbsp;
      <span>部门:&nbsp;<u>{{noteDetail.departmentId}}</u></span>&nbsp;&nbsp;|&nbsp;&nbsp;
      <span>发布时间:&nbsp;{{noteDetail.createTime}}</span>
    </h4>

    <el-text class="mx-1" size="large">{{noteDetail.content}}</el-text>
  </el-dialog>

</template>

<script setup>
import { Warning,} from '@element-plus/icons-vue'
// import axios  from "axios";
import axios from "@/http";
import {onMounted, ref} from "vue";
import {ElMessage} from "element-plus";
import qs from "qs";
import router from "@/router";

const assetCount = ref(0);
const userCount = ref(0);
const deptCount = ref(0);
const atteCount = ref(0);
const currentTime = ref();
const searchAnno = ref({});
const annoList = ref([]);
const noteList = ref([]);
const currentPage = ref(1);
const currentSize = ref(10);
const total = ref(100);
const currentPageB = ref(1);
const currentSizeB = ref(10);
const totalB = ref(100);

const handleCurrentChange = (val) => {
  loadAnno();
}
const handleCurrentChangeB = (val) => {
  loadNote();
}

const loadDataNum = () => {
  // 固定资产数
  axios.get(BASE_URL+'/oa/asset/count').then((response)=>{
    if(response.data.code == 20000){
      assetCount.value = response.data.data;
    }else {
      ElMessage.error(response.data.msg);
    }
  })

  //员工数
  axios.get(BASE_URL+'/oa/user/count').then((response)=>{
    if(response.data.code == 20000){
      userCount.value = response.data.data;
    }else {
      ElMessage.error(response.data.msg);
    }
  })

  //部门数
  axios.get(BASE_URL+'/oa/department/count').then((response)=>{
    if(response.data.code == 20000){
      deptCount.value = response.data.data;
    }else {
      ElMessage.error(response.data.msg);
    }
  })
  //打卡数
  axios.get(BASE_URL+'/oa/attendance/count').then((response)=>{
    if(response.data.code == 20000){
      atteCount.value = response.data.data;
    }else {
      ElMessage.error(response.data.msg);
    }
  })

}

//公告
const loadAnno = () => {
  //TODO searchAnno 按全局id找部门id>显示部门可见+全部人可见
  searchAnno.value.pageSize = currentSize.value;
  searchAnno.value.pageNum = currentPage.value;
  let data = qs.stringify(searchAnno.value);
  axios.get(BASE_URL+'/oa/announcement/select?'+data).then((response)=>{
    if(response.data.code == 20000){
      annoList.value = response.data.data.list;
      total.value = response.data.data.total;
    }else {
      ElMessage.error(response.data.msg);
    }
  })
}
//公告详情
const annoVisible = ref(false);
const annoDetail = ref({});

const showAnno = (id) => {
  annoVisible.value = true;
  axios.get('/oa/announcement/show?id=' + id).then((response) => {
    if (response.data.code == 20000) {
      annoDetail.value = response.data.data;
    } else {
      ElMessage.error(response.data.msg);
    }
  })
}

const handleChange = (val) => {
  console.log(val.id);
  if(val.id!= null){
    showAnno(val.id);
  }
}
const handleChangeB = (val) => {
  console.log(val.id);
  if(val.id!= null){
    showNote(val.id);
  }
}

//备忘
const loadNote = ()=>{
  //TODO searchAnno 按全局id找部门id>显示部门可见+全部人可见
  noteList.value.pageSize = currentSizeB.value;
  noteList.value.pageNum = currentPageB.value;
  let data = qs.stringify(noteList.value);
  axios.get(BASE_URL+'/oa/note/select?'+data).then((response)=>{
    if(response.data.code == 20000){
      noteList.value = response.data.data.list;
      totalB.value = response.data.data.total;
    }else {
      ElMessage.error(response.data.msg);
    }
  })
}

//备忘详情
const noteVisible = ref(false);
const noteDetail = ref({});

const showNote = (id) => {
  noteVisible.value = true;
  axios.get('/oa/note/show?id=' + id).then((response) => {
    if (response.data.code == 20000) {
      noteDetail.value = response.data.data;
    } else {
      ElMessage.error(response.data.msg);
    }
  })
}


onMounted(()=>{
  loadDataNum();
  loadAnno();
  loadNote();
})



//JS实时时钟
const getTime = () => {
  const  now = new Date();
    currentTime.value = now.getFullYear() + '  年  ' +
        (now.getMonth() + 1) + '  月  ' +
        now.getDate() + '  日  ' +
        now.toLocaleTimeString();
}

setInterval(()=>{
  getTime(),1000
})

const toAtt = () => {
  router.push('/attendance')
}

const toEmp = () => {
  router.push('/user')
}

const toAsset = () => {
  router.push('/asset')
}

const toVehicle = () => {
  router.push('/vehicle')
}

const toRepair = () => {
  router.push('/repair')
}

const toNote = () => {
  router.push('/note')
}

</script>

<script>

import axios from "@/http";
import {ElMessage} from "element-plus";
import {onMounted} from "vue";

export default {
  data() {
    return {
      socket: null,
      messages: [],
      unreadCount: 0,   // 未读消息计数
      socket2: null,
      messages2: [],
      unreadCount2: 0,   // 未读消息计数
      socket3: null,
      messages3: [],
      unreadCount3: 0,   // 未读消息计数
      socket4: null,
      messages4: [],
      unreadCount4: 0,   // 未读消息计数
      socket5: null,
      messages5: [],
      unreadCount5: 0,   // 未读消息计数
      socket6: null,
      messages6: [],
      unreadCount6: 0,   // 未读消息计数
    };
  },

  mounted() {
    this.connect(); // 组件挂载后，建立 WebSocket 连接
  },
  methods: {
    connect() {
      // // 获取 JWT token
      // const token = localStorage.getItem('token');
      //
      // // 解析 JWT token 获取 userId
      // function getUserIdFromToken(token) {
      //   if (!token) return null;
      //   const payload = token.split('.')[1]; // 获取中间部分
      //   const decodedPayload = JSON.parse(atob(payload)); // 解码为对象
      //   return decodedPayload.userId; // 获取 userId
      // }
      //
      // const userId = getUserIdFromToken(token);
      //
      // console.log('Token:', token);
      // console.log('User ID:', userId);
      // 使用原生 WebSocket 连接
      this.socket = new WebSocket("ws://localhost:8080/websocket-endpoint?userId=1");
      this.socket2 = new WebSocket("ws://localhost:8080/websocket-endpoint?userId=2");
      this.socket3 = new WebSocket("ws://localhost:8080/websocket-endpoint?userId=3");
      this.socket4 = new WebSocket("ws://localhost:8080/websocket-endpoint?userId=4");
      this.socket5 = new WebSocket("ws://localhost:8080/websocket-endpoint?userId=5");
      this.socket6 = new WebSocket("ws://localhost:8080/websocket-endpoint?userId=6");
      this.socket.onopen = () => {
        console.log("WebSocket connected");
      };this.socket2.onopen = () => {
        console.log("WebSocket connected");
      };this.socket3.onopen = () => {
        console.log("WebSocket connected");
      };this.socket4.onopen = () => {
        console.log("WebSocket connected");
      };this.socket5.onopen = () => {
        console.log("WebSocket connected");
      };this.socket6.onopen = () => {
        console.log("WebSocket connected");
      };
      this.socket.onmessage = (event) => {
        const receivedMessage = JSON.parse(event.data);
        console.log("Received message:", receivedMessage);
        this.messages.push(receivedMessage);
        this.unreadCount++;  // 增加未读消息计数
      };
      this.socket2.onmessage = (event) => {
        const receivedMessage = JSON.parse(event.data);
        console.log("Received message:", receivedMessage);
        this.messages2.push(receivedMessage);
        this.unreadCount2++;  // 增加未读消息计数
      };
      this.socket3.onmessage = (event) => {
        const receivedMessage = JSON.parse(event.data);
        console.log("Received message:", receivedMessage);
        this.messages3.push(receivedMessage);
        this.unreadCount3++;  // 增加未读消息计数
      };
      this.socket4.onmessage = (event) => {
        const receivedMessage = JSON.parse(event.data);
        console.log("Received message:", receivedMessage);
        this.messages4.push(receivedMessage);
        this.unreadCount4++;  // 增加未读消息计数
      };
      this.socket5.onmessage = (event) => {
        const receivedMessage = JSON.parse(event.data);
        console.log("Received message:", receivedMessage);
        this.messages5.push(receivedMessage);
        this.unreadCount5++;  // 增加未读消息计数
      };
      this.socket6.onmessage = (event) => {
        const receivedMessage = JSON.parse(event.data);
        console.log("Received message:", receivedMessage);
        this.messages6.push(receivedMessage);
        this.unreadCount6++;  // 增加未读消息计数
      };
      this.socket.onclose = () => {
        console.log("WebSocket disconnected");
      };
      this.socket2.onclose = () => {
        console.log("WebSocket disconnected");
      };
      this.socket3.onclose = () => {
        console.log("WebSocket disconnected");
      };
      this.socket4.onclose = () => {
        console.log("WebSocket disconnected");
      };
      this.socket5.onclose = () => {
        console.log("WebSocket disconnected");
      };
      this.socket6.onclose = () => {
        console.log("WebSocket disconnected");
      };
      this.socket.onerror = (error) => {
        console.error("WebSocket error:", error);
      };
      this.socket2.onerror = (error) => {
        console.error("WebSocket error:", error);
      };
      this.socket3.onerror = (error) => {
        console.error("WebSocket error:", error);
      };
      this.socket4.onerror = (error) => {
        console.error("WebSocket error:", error);
      };
      this.socket5.onerror = (error) => {
        console.error("WebSocket error:", error);
      };
      this.socket6.onerror = (error) => {
        console.error("WebSocket error:", error);
      };
    },
    showMessages() {
      this.unreadCount = 0;
    },
    showMessages2() {
      this.unreadCount2 = 0;
    },
    showMessages3() {
      this.unreadCount3 = 0;
    },
    showMessages4() {
      this.unreadCount4 = 0;
    },
    showMessages5() {
      this.unreadCount5 = 0;
    },
    showMessages6() {
      this.unreadCount6 = 0;
    }
  }
};

const vehicle = () => {
  axios.get(BASE_URL+'/oa/asset/vehicle/addNum').then((response)=>{
    if(response.data.code == 20000){
      console.log(response.data)
    }else {
      ElMessage.error(response.data)
    }
  })
}
const asset = () => {
  axios.get(BASE_URL+'/oa/asset/addNum').then((response)=>{
    if(response.data.code == 20000){
      console.log(response.data)
    }else {
      ElMessage.error(response.data)
    }
  })
}
const announcement = () => {
  axios.get(BASE_URL+'/oa/announcement/addNum').then((response)=>{
    if(response.data.code == 20000){
      console.log(response.data)
    }else {
      ElMessage.error(response.data)
    }
  })
}
const attendance = () => {
  axios.get(BASE_URL+'/oa/asset/attendance/addNum').then((response)=>{
    if(response.data.code == 20000){
      console.log(response.data)
    }else {
      ElMessage.error(response.data)
    }
  })
}
const repair = () => {
  axios.get(BASE_URL+'/oa/asset/repair/addNum').then((response)=>{
    if(response.data.code == 20000){
      console.log(response.data)
    }else {
      ElMessage.error(response.data)
    }
  })
}
const note = () => {
  axios.get(BASE_URL+'/oa/note/addNum').then((response)=>{
    if(response.data.code == 20000){
      console.log(response.data)
    }else {
      ElMessage.error(response.data)
    }
  })
}
const user = () => {
  axios.get(BASE_URL+'/oa/sys/user/addNum').then((response)=>{
    console.log(response);
    if(response.data.code == 20000){
    }else {
      ElMessage.error(response.data)

    }
  })
}

// OnMounted(()=>{
//   note();
//   attendance();
//   repair();
//   vehicle();
//   announcement();
//   asset();
//   user();
// });

</script>

<style scoped>
:global(h2#card-usage ~ .example .example-showcase) {
  background-color: var(--el-fill-color) !important;
}

.el-statistic {
  --el-statistic-content-font-size: 30px;
}

.statistic-card {
  height: 100%;
  //padding: 20px;
  border-radius: 4px;
  text-align: center;
  font-weight: bolder;
  box-shadow: #333333 0 3px ;
}

.sub_title {
  font-size: 20px;
  font-weight: bolder;
  color: #2c3e50;
  text-align: center;
}

.dot_title {
  position: absolute;
  font-size: 40px;
  margin-top: 0;
  text-decoration: underline;
}

.message-icon {
  position: absolute;
  cursor: pointer;
  top: -15px;
  left: 110px;
}

.badge {
  display: inline-block;
  min-width: 20px;
  padding: 3px 7px;
  font-size: 12px;
  font-weight: bold;
  color: white;
  background-color: red;
  border-radius: 10px;
  position: absolute;
  top: 5px;
  right: 5px;
}

.block {
  position: relative;
}
</style>
